/**
 * @package 全局异常捕获过滤器
 * @author liu
 */

import {
  ArgumentsHost,
  Catch,
  ExceptionFilter,
  HttpException,
  HttpStatus,
  Logger
} from '@nestjs/common'

import type { Request, Response } from 'express'

@Catch(HttpException)
export class HttpExceptionFilter implements ExceptionFilter {
  constructor(private readonly logger: Logger) {}

  catch(exception: HttpException, host: ArgumentsHost) {
    const ctx = host.switchToHttp()
    const request = ctx.getRequest<Request>()
    const response = ctx.getResponse<Response>()
    const status =
      exception instanceof HttpException
        ? exception.getStatus()
        : HttpStatus.INTERNAL_SERVER_ERROR

    const data =
      (exception.getResponse() as any)?.message ?? exception.message ?? null

    const timestamp = (Date.now() + 1000 * 60 * 60 * 8).toString()

    const message = status == 401 ? '登录超时' : '请求错误'

    const errorResponse = {
      message,
      code: status,
      success: false,
      timestamp,
      method: request.method,
      url: request.url,
      data
    }

    this.logger.error(
      `[${timestamp}] ${request.method} ${request.url} query: ${JSON.stringify(
        request.query
      )} params: ${JSON.stringify(request.params)} body: ${JSON.stringify(
        request.body
      )}`,
      JSON.stringify(errorResponse),
      'HttpExceptionFilter'
    )

    response.status(status).header('').json(errorResponse)
  }
}
